package com.cmcc.passenger.ui.order

import android.os.Bundle
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.passenger.R
import com.cmcc.passenger.config.PassPath
import com.cmcc.passenger.data.entity.OrderRecordItem
import com.cmcc.passenger.databinding.ActivityMyOrderBinding
import com.cmcc.passenger.ui.base.BasicActivity
import com.cmcc.passenger.ui.order.adapter.MyOrderItemClickListener
import com.cmcc.passenger.ui.order.adapter.OrderRecordAdapter
import com.cmcc.passenger.ui.profile.SpaceItemDecoration
import com.cmcc.shared.utils.DisplayUtil

@Route(path = PassPath.MY_ORDER)
class MyOrderActivity : BasicActivity() {

    private lateinit var binding: ActivityMyOrderBinding

    private lateinit var viewModel: MyOrderViewModel

    private var adapter: OrderRecordAdapter? = null

    private var lastPage = 0
    private var currentPage = 1
    private val pageSize = 10
    private var lastVisibleItemPosition: Int = -1

    override fun initialize(savedInstanceState: Bundle?) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_my_order)
        viewModel = ViewModelProviders.of(this).get(MyOrderViewModel::class.java)
        binding.toolbars.title.text = getString(R.string.passenger_personal_order)
        binding.toolbars.toolbar.setNavigationOnClickListener { finish() }
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.addItemDecoration(
            SpaceItemDecoration(
                DisplayUtil.dp2px(this, 8f).toInt()
            )
        )
        adapter = OrderRecordAdapter()
        binding.swipeRefreshLayout.isRefreshing = true
        viewModel.getOrderRecords(currentPage, pageSize)
        adapter?.addItemClickListener(onItemClickListener())
        binding.recyclerView.adapter = adapter
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val layoutManager = recyclerView.layoutManager
                if (layoutManager is LinearLayoutManager) {
                    lastVisibleItemPosition =
                        layoutManager.findLastVisibleItemPosition()
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                    && lastVisibleItemPosition + 1 == recyclerView.adapter?.itemCount
                ) {
                    if (currentPage > lastPage)
                        viewModel.getOrderRecords(currentPage, pageSize)
                }
            }
        })
        binding.swipeRefreshLayout.setColorSchemeColors(resources.getColor(R.color.passenger_colorAccents))
        binding.swipeRefreshLayout.setOnRefreshListener {
            viewModel.getOrderRecords(0, pageSize)
        }
    }

    override fun initObserver(savedInstanceState: Bundle?) {
        viewModel.orderRecords.observe(this, Observer { response ->
            binding.swipeRefreshLayout.isRefreshing = false
            lastPage = currentPage
            if (currentPage <= response.pages) {

                var currentList = mutableListOf<OrderRecordItem>()
                if (currentPage == 1) {
                    var processItem = OrderRecordItem()
                    processItem.itemType = 1
                    currentList.add(processItem)
                }
                response.list.forEach { orderRecord ->
                    if(orderRecord.status != 6 && orderRecord.status != 7){
                        var orderRecordItem =  OrderRecordItem()
                        orderRecordItem.itemType = 0
                        orderRecordItem.orderRecord = orderRecord
                        currentList.add(orderRecordItem)
                    }
                }

                if (currentPage == 1) {
                    var completedItem =  OrderRecordItem()
                    completedItem.itemType = 2
                    currentList.add(completedItem)
                }

                response.list.forEach { orderRecord ->
                    if(orderRecord.status == 6 || orderRecord.status == 7){
                        var orderRecordItem =  OrderRecordItem()
                        orderRecordItem.itemType = 0
                        orderRecordItem.orderRecord = orderRecord
                        currentList.add(orderRecordItem)
                    }
                }

                adapter?.addList(currentList)
                currentPage += 1
            }
        })
    }

    var mLastClickTime: Long = 0
    val TIME_INTERVAL = 1000L

    private fun onItemClickListener(): MyOrderItemClickListener {
        return object :
            MyOrderItemClickListener {
            override fun click(
                binding: View,
                model: OrderRecordItem
            ) {
                when(model.orderRecord.handleMode) {
                    2 -> {
                        ARouter.getInstance().build(PassPath.CALL_ORDER_DETAIL)
                            .withString("order_id", model.orderRecord.id)
                            .withInt("flag", 1)
                            .navigation()
                    }
                    else -> {
                        val nowTime = System.currentTimeMillis()
                        if (nowTime - mLastClickTime > TIME_INTERVAL) {
                            mLastClickTime = nowTime
                            ARouter.getInstance().build(PassPath.ORDER_DETAIL)
                                .withString("order_id", model.orderRecord.id)
                                .navigation()
                        }
                    }
                }
            }
        }
    }
}
